//
//  PreOrderViewController.swift
//  AutoPrint
//
//  Created by 胡玉葱 on 16/9/28.
//  Copyright © 2016年 fatcat. All rights reserved.
//  提交订单页面

import UIKit

class PreOrderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate, AddressReturnPreOrder, FileUploadViewDelegate, UIDocumentInteractionControllerDelegate {

    let DOCUMENT_PATH = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
    
    let ASK_BEFORE_EXIT_ALERT_ID = 101
    let QUANTITY_INPUT_ID = 102
    
    var tableView: UITableView!
    
    var files: [UDFile] = [] // 文件列表
    var fileUploadControls: [FileUploadView] = [] // 文件上传控制
    
    var getGoodsMethod = 1 // 配送方式
    
    var localAddress: NSDictionary? // 选择的收货地址
    var selectedAddressInt = 0 // 选择的收货地址在本地列表中的索引位置
    var addressLabel1: UILabel! // 显示省市区的label
    var addressLabel2: UILabel! // 显示详细地址的label
    var addressLabel3: UILabel! // 显示名字和电话的label
    
    
    var totalPriceLabel: UILabel! // 底部合计多少钱的label
    var totalPrice:Double = 0.0 // 一共多少钱
    var totalPageNum:Int = 0 // 一共多少张纸
    
    var totalCutOff:Double = 0.0 // 一共优惠多少
    var cutOffList: NSMutableArray! // 优惠列表
    
    var bottomBar: UIView! // 底部栏
    var submitBtn: UIButton! // 提交订单按钮
    
    var payMethod:Int = 0 // 支付方式
    var commentInput:UITextField! // 备注输入框

    var submitting = false // 提交ing
    
    var loadingSpinner: UIView!
    var actIndi: UIActivityIndicatorView!
    var msgLabel: UILabel!
    var retryBtn: UIButton!
    var statusIcon: UIImageView!
    
    convenience init(files: [UDFile]){
        self.init()
        self.files = files
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        title = "提交订单"
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: #selector(PreOrderViewController.askBeforeExit))
        
        tableView = UITableView(frame: view.frame, style: .Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = .OnDrag
        tableView.separatorStyle = .None
        view.addSubview(tableView)
        
        // MARK: 读本地收货地址
        if NSFileManager.defaultManager().fileExistsAtPath("\(DOCUMENT_PATH)/address.plist") {
            let addressAry = NSArray(contentsOfFile: "\(DOCUMENT_PATH)/address.plist")
            localAddress = addressAry?.objectAtIndex(selectedAddressInt) as? NSDictionary
        }
        addressLabel1 = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width-32, height: 16))
        addressLabel2 = UILabel(frame: CGRect(x: 16, y: 32, width: view.bounds.width-32, height: 16))
        addressLabel3 = UILabel(frame: CGRect(x: 16, y: 56, width: view.bounds.width-32, height: 16))
        
        // MARK: progress retryBtn 做成对象数组 支持多文件上传
        for file in files{
            let fileControl = FileUploadView(file: file)
            fileControl.delegate = self
            fileUploadControls.append(fileControl)
            fileControl.checkFile()
        }
        
        // MARK: 底部栏
        bottomBar = UIView(frame: CGRect(x: -0.5, y: view.bounds.height - 48, width: view.bounds.width+1, height: 48))
        bottomBar.backgroundColor = UIColor.whiteColor()
        bottomBar.layer.borderColor = UIColor.lightGrayColor().CGColor
        bottomBar.layer.borderWidth = 0.5
        
        view.addSubview(bottomBar)
        
        // MARK: 底部显示合计
        totalPriceLabel = UILabel(frame: CGRect(x: 16, y: 8, width: 120, height: 32))
        bottomBar.addSubview(totalPriceLabel)
        
        // MARK:提交按钮
        submitBtn = UIButton(frame: CGRect(x: view.bounds.width - 119, y: 0, width: 120, height: 48))
        submitBtn.backgroundColor = UIColor.lightGrayColor()
        submitBtn.setTitle("提交订单", forState: .Normal)
        submitBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        submitBtn.enabled = false
        bottomBar.addSubview(submitBtn)
        submitBtn.addTarget(self, action: #selector(PreOrderViewController.submitOrder), forControlEvents: .TouchUpInside)
        
        // MARK: 备注输入框
        commentInput = UITextField(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: 28))
        commentInput.tag = 101
        commentInput.placeholder = "留下你的备注，比如装订等等"
        commentInput.addTarget(self, action: #selector(PreOrderViewController.textFieldScrollUp(_:)), forControlEvents: .EditingDidBegin)
        
        // MARK: 优惠列表
        cutOffList = NSMutableArray()
        
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 5
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 4*files.count // 文档相关的参数 页数，份数显示在这里
        case 1:
            if getGoodsMethod == 1{
                return 2
            }
            return 3 // 收获地址显示在这里
        case 2:
            return 1
        case 3:
            return files.count+2 // 合计
        case 4:
            return Fatcat.payMethods.count // 支付方式显示在这里
        default:
            return 1
        }
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row % 4 == 0{
            return 64
        }
        if indexPath.section == 0 && indexPath.row % 4 == 3{
            return 52
        }
        if getGoodsMethod == 2{
            if indexPath.section == 1 && indexPath.row == 2{
                return 80
            }
        }
        
        if indexPath.section == 3{
            return 30
        }
        return 44
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 16
    }
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch section {
        case 1:
            return "取件方式"
        case 2:
            return "备注"
        case 3:
            return "合计"
        case 4:
            return "支付方式"
        default:
            return nil
        }
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 4{
            return 72
        }
        return 0
    }
    func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        if indexPath.section == 1{
            return indexPath
        }
        if indexPath.section == 4{
            return indexPath
        }
        return nil
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "file")
        switch indexPath.section {
        case 0:
            let fileIndex = indexPath.row / 4
            let order = indexPath.row % 4
            switch order {
            case 0: // MARK: 上传文件
                cell.addSubview(fileUploadControls[fileIndex].createUploadView(cell.frame))
                
                break
            case 1: // MARK: 页数
                cell.addSubview(fileUploadControls[fileIndex].createPageNumView(cell.frame))
                
                break
            case 2:// MARK: 单面双面 黑白彩印
                cell.addSubview(fileUploadControls[fileIndex].createOptionView(cell.frame))
                break
            case 3: // MARK: 份数
                cell.addSubview(fileUploadControls[fileIndex].createQuantityView(cell.frame, index: indexPath.row/4))
                break
                
            default:
                break
            }
            break
        case 1:
            switch indexPath.row {
            case 0:
                let textLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width-32, height: 28))
                cell.addSubview(textLabel)
                
                textLabel.text = "自助取件"
                
                if getGoodsMethod == 1{
                    cell.accessoryType = .Checkmark
                }
                
                let sep = UIView(frame: CGRect(x: 16, y: 43.5, width: view.bounds.width - 16, height: 0.5))
                sep.backgroundColor = UIColor.lightGrayColor()
                cell.addSubview(sep)
                
                break
            case 1:
                let textLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width-32, height: 28))
                cell.addSubview(textLabel)
                
                textLabel.text = "校内配送"
                if getGoodsMethod == 2{
                    cell.accessoryType = .Checkmark
                }
                let sep = UIView(frame: CGRect(x: 16, y: 43.5, width: view.bounds.width - 16, height: 0.5))
                sep.backgroundColor = UIColor.lightGrayColor()
                cell.addSubview(sep)
                break
            case 2: // MARK: 收货地址 && 配送方式
                cell.addSubview(addressLabel1)
                cell.addSubview(addressLabel2)
                cell.addSubview(addressLabel3)
                if localAddress == nil{
                    
                    addressLabel1.text = "请选择收货地址"
                    
                }else{
                    
                    
                    
                    
                    addressLabel1.text = "\(localAddress?.objectForKey("province") as! String) \(localAddress?.objectForKey("city") as! String) \(localAddress?.objectForKey("precinct") as! String) "
                    addressLabel2.text = localAddress?.objectForKey("specify") as? String
                    addressLabel3.text = "\(localAddress?.objectForKey("receiver") as! String) \(localAddress?.objectForKey("phone") as! String)"
                    
                }
                cell.accessoryType = .DisclosureIndicator
                break
            default:
                break
            }
            break
        case 2:
            cell.addSubview(commentInput)
            break
        case 3: // MARK: 显示页数x份数 合计多少钱
            
            let infoLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width/2 - 32, height: 16))
            infoLabel.font = UIFont.systemFontOfSize(14)
            cell.addSubview(infoLabel)
            
            let priceLabel = UILabel(frame: CGRect(x: view.bounds.width/2, y: 8, width: view.bounds.width/2 - 16, height: 16))
            priceLabel.font = UIFont.systemFontOfSize(14)
            priceLabel.textAlignment = .Right
            priceLabel.textColor = UIColor.lightGrayColor()
            cell.addSubview(priceLabel)
            
            priceLabel.text = "￥ 0"
            
            if indexPath.row < fileUploadControls.count{
                let pageNum = fileUploadControls[indexPath.row].numOfPage
                let quantity = fileUploadControls[indexPath.row].numOfQuantity
                
                infoLabel.text = "\(pageNum)页 x \(quantity)份"
                if fileUploadControls[indexPath.row].blackWhiteColorOption == 1{
                    priceLabel.text = "￥ \(Double(pageNum * quantity) * Fatcat.PRICE_PRE_PAGE)"
                }else{
                    priceLabel.text = "￥ \(Double(pageNum * quantity) * Fatcat.PRICE_PRE_COLOR_PAGE)"
                }
                
            }else{
                if indexPath.row == fileUploadControls.count {
                    infoLabel.text = "运费"
                    if getGoodsMethod == 2{
                        priceLabel.text = "￥ \(Fatcat.DELIVER_PRICE)"
                    }
                    
                    
                }else if indexPath.row == fileUploadControls.count + 1{
                    infoLabel.text = "优惠"
                    if totalPageNum >= Fatcat.FREE_DELIVER_MIN{
                        priceLabel.text = "- ￥ \(totalCutOff)"
                    }
                }
                
            }
            
            
            break
        case 4:
            switch indexPath.row {
            case 0: // MARK: 选择支付方式的view
                let icon = UIImageView(frame: CGRect(x: 16, y: 8, width: 28, height: 28))
                //icon.backgroundColor = UIColor.lightGrayColor()
                cell.addSubview(icon)
                
                // TODO: 支付宝icon
                icon.image = UIImage(named: "alipay")
                let nameLabel = UILabel(frame: CGRect(x: 52, y: 8, width: view.bounds.width - 80, height: 28))
                cell.addSubview(nameLabel)
                
                /*
                let subLabel = UILabel(frame: CGRect(x: 72, y: 36, width: view.bounds.width - 80, height: 20))
                subLabel.textColor = UIColor.lightGrayColor()
                cell.addSubview(subLabel)
                */
                
                nameLabel.text = "支付宝"
                break
            default:
                break
            }
            if indexPath.row == payMethod{
                cell.accessoryType = .Checkmark
            }
            break
        default:
            break
        }
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        if indexPath.section == 1{
            if indexPath.row == 2 { // MARK: 点击进入收货地址选择
                hidesBottomBarWhenPushed = true
                let addressMan = AdressManageViewController(managerType: .Select)
                addressMan.currentSelected = selectedAddressInt
                addressMan.delegate = self //TODO: 代理有时调用不了，试试addressMan全局
                navigationController?.pushViewController(addressMan, animated: true)
            }else{
                // MARK: 选择配送方式
                getGoodsMethod = indexPath.row + 1
                
                tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic)
                didUpdatePrice()
            }
            
        }
        
        if indexPath.section == 4{ // MARK: 选择支付方式
            payMethod = indexPath.row
            tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic)
        }
    }

    
    
    func askBeforeExit(){
        // MARK: 询问是否退出
        
        let alert = UIAlertView(title: "你的订单还没提交", message: "确定要退出吗?", delegate: self, cancelButtonTitle: "不退出")
        if submitting {
            alert.title = "你的订单还没支付"
            alert.message = "你可以在\(Fatcat.ORDER_UNPAY_EXPIRE_TIME)分钟内对此订单支付，否则自动退单"
        }
        alert.tag = ASK_BEFORE_EXIT_ALERT_ID
        alert.addButtonWithTitle("退出")
        alert.show()
        
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if alertView.tag == ASK_BEFORE_EXIT_ALERT_ID {
            if buttonIndex == 1{
                navigationController?.popViewControllerAnimated(true)
                //MARK:MAY: 调用退出接口
            }
        }
    }
    func textFieldScrollUp(textField: UITextField) {
        // MARK: 输入框被键盘遮盖时往上移动
        if textField.tag == commentInput.tag{
            var height = CGFloat(fileUploadControls.count)*204 + 32 + 88 + 32
            if getGoodsMethod == 2{
                height += 80
            }
            height = height - view.bounds.height/2 + 128
            if tableView.contentOffset.y < height{
                tableView.setContentOffset(CGPoint(x: 0, y: height), animated: true)
            }
        }else{
            if tableView.contentOffset.y < CGFloat(textField.tag)*204 - 32{
                tableView.setContentOffset(CGPoint(x: 0, y: CGFloat(textField.tag)*204 - 32), animated: true)
            }
        }
        
    }
    func didUpdatePrice() {
        // MARK: 更新价格
        //更改页数 份数 单面双面 黑白彩印 配送方式 这些参数之后调用的代理
        totalPrice = 0.0
        totalCutOff = 0.0
        totalPageNum = 0
        var orderReady = true
        for control in fileUploadControls{
            let pageNum = control.numOfPage
            let quantity = control.numOfQuantity
            totalPageNum += pageNum*quantity
            if control.blackWhiteColorOption == 1{
                totalPrice += Double(pageNum*quantity)*Fatcat.PRICE_PRE_PAGE
            }else{
                totalPrice += Double(pageNum*quantity)*Fatcat.PRICE_PRE_COLOR_PAGE
            }
            
            if !control.isFinishedUpload{
                orderReady = false
            }
        }
        
        if getGoodsMethod == 2 {
            totalPrice += Fatcat.DELIVER_PRICE
            if totalPageNum >= Fatcat.FREE_DELIVER_MIN{
                totalCutOff += Fatcat.DELIVER_PRICE
            }
            totalPrice -= totalCutOff
        }
        
        
        tableView.reloadSections(NSIndexSet(index: 3), withRowAnimation: .None)
        
        if orderReady{
            totalPriceLabel.text = "合计: ¥ \(totalPrice)"
            submitBtn.backgroundColor = UIColor.orangeColor()
            submitBtn.enabled = true
        }
//        let totalPriceStr = "合计: ¥ \(totalPrice)"
//        let attrStr = NSMutableAttributedString(string: totalPriceStr)
//        
//        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: NSMakeRange(3, totalPriceStr.characters.count))
        
    }

    
    func setShownAdress(address: NSDictionary, atIndex: Int) {
        // MARK: 选择收货地址后调用的代理
        selectedAddressInt = atIndex
        localAddress = NSDictionary(dictionary: address)
        addressLabel1.text = "\(localAddress?.objectForKey("province") as! String) \(localAddress?.objectForKey("city") as! String) \(localAddress?.objectForKey("precinct") as! String) "
        addressLabel2.text = localAddress?.objectForKey("specify") as? String
        addressLabel3.text = "\(localAddress?.objectForKey("receiver") as! String) \(localAddress?.objectForKey("phone") as! String)"
    }
    
    func submitOrder(){
        // TODO: 提交订单
        
        let submitBody = NSMutableDictionary()
        
        
        
        if getGoodsMethod == 2{
            submitBody.setObject("", forKey: "province")
            submitBody.setObject("", forKey: "city")
            submitBody.setObject("", forKey: "area")
            submitBody.setObject("", forKey: "address")
            submitBody.setObject("", forKey: "name")
            submitBody.setObject("", forKey: "phone")
            
            if localAddress != nil {
                submitBody.setObject(localAddress?.objectForKey("province") as! String, forKey: "province")
                submitBody.setObject(localAddress?.objectForKey("city") as! String, forKey: "city")
                submitBody.setObject(localAddress?.objectForKey("precinct") as! String, forKey: "area")
                submitBody.setObject(localAddress?.objectForKey("specify") as! String, forKey: "address")
                submitBody.setObject(localAddress?.objectForKey("receiver") as! String, forKey: "name")
                submitBody.setObject(localAddress?.objectForKey("phone") as! String, forKey: "phone")
            }else{
                UIAlertView(title: "请填写收货地址", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                return
            }
        }
        submitBody.setObject(totalPrice, forKey: "totalPrice")
        submitBody.setObject(Fatcat.payMethods[payMethod], forKey: "payMethod")
        submitBody.setObject(getGoodsMethod, forKey: "postMethod")
        submitBody.setObject("", forKey: "remark")
        if commentInput.text != nil {
            submitBody.setObject(commentInput.text!, forKey: "remark")
        }
        
        let fileInfos = NSMutableArray()
        for file in fileUploadControls{
            let info = NSMutableDictionary()
            info.setObject(file.fileID!, forKey: "file_id")
            info.setObject(file.numOfQuantity, forKey: "goods_number")
            info.setObject(file.blackWhiteColorOption, forKey: "black_white_color")
            info.setObject(file.singleDoublePageOption, forKey: "single_double")
            
            if file.blackWhiteColorOption == 1 {
                info.setObject(Fatcat.PRICE_PRE_PAGE, forKey: "goods_price")
            }else if file.blackWhiteColorOption == 2{
                info.setObject(Fatcat.PRICE_PRE_COLOR_PAGE, forKey: "goods_price")
            }
            
            fileInfos.addObject(info)
        }
        submitBody.setObject(fileInfos, forKey: "fileInfos")
        
        let json = try? NSJSONSerialization.dataWithJSONObject(submitBody, options: .PrettyPrinted)
        if json != nil{
            print(NSString(data: json!, encoding: NSUTF8StringEncoding))
            let postResq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
            postResq.HTTPMethod = "POST"
            let postData = NSMutableData()
            postData.appendData(NSString(string: "act=submitOrder&json=").dataUsingEncoding(NSUTF8StringEncoding)!)
            postData.appendData(json!)
            postResq.HTTPBody = postData
            
            // MARK:开始提交
            submitting = true
            submitBtn.enabled = false
            submitBtn.setTitle("请稍后...", forState: .Normal)
            submitBtn.backgroundColor = UIColor.lightGrayColor()
            
            // MARK: 加载菊花 务必放在最顶层
            loadingSpinner = UIView(frame: view.frame)
            loadingSpinner.backgroundColor = UIColor(white: 0, alpha: 0.6)
            actIndi = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
            actIndi.center = loadingSpinner.center
            actIndi.startAnimating()
            loadingSpinner.addSubview(actIndi)
            view.addSubview(loadingSpinner)
            
            self.msgLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 20))
            self.msgLabel.center.x = self.view.center.x
            self.msgLabel.center.y = self.view.center.y + 48
            self.msgLabel.font = UIFont.systemFontOfSize(14)
            self.msgLabel.text = "提交成功，正在前往支付"
            self.msgLabel.textColor = UIColor.whiteColor()
            self.msgLabel.textAlignment = .Center
            self.view.addSubview(self.msgLabel)
            self.msgLabel.alpha = 0
            
            self.statusIcon = UIImageView(image: UIImage(named: "warning"))
            self.statusIcon.center = self.view.center
            self.loadingSpinner.addSubview(self.statusIcon)
            self.statusIcon.alpha = 0
            
            self.retryBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 28))
            self.retryBtn.center = CGPoint(x: self.view.center.x, y: self.view.center.y + 80)
            self.retryBtn.setTitle("重试", forState: .Normal)
            self.retryBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
            self.retryBtn.layer.cornerRadius = 4
            self.retryBtn.layer.borderColor = UIColor.whiteColor().CGColor
            self.retryBtn.layer.borderWidth = 1
            self.loadingSpinner.addSubview(self.retryBtn)
            self.retryBtn.addTarget(self, action: #selector(PreOrderViewController.handlePayment), forControlEvents: .TouchUpInside)
            self.retryBtn.alpha = 0
            
            NSURLSession.sharedSession().dataTaskWithRequest(postResq, completionHandler: { (reData:NSData?, resp:NSURLResponse?, err:NSError?) in
                var failed = true
                var errMsg:String?
                if err == nil{
                    if let data = reData{
                        print("return data: \(NSString(data: data, encoding: NSUTF8StringEncoding))")
                        let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
                        if jsonObj != nil{
                            let jsonDic = jsonObj as! NSDictionary
                            let reCode = jsonDic.objectForKey("code") as? Int
                            if reCode == 200{
                                failed = false
                                NSUserDefaults.standardUserDefaults().setObject(true, forKey: "orderListRefreshRequire")
                                // TODO: 调用支付接口
                                dispatch_async(dispatch_get_main_queue(), { 
                                    
                                    UIView.animateWithDuration(1, animations: {
                                        self.msgLabel.alpha = 1
                                        
                                        
                                    })
                                    
                                    self.handlePayment()
                                })
                            }else{
                                errMsg = jsonDic.objectForKey("message") as? String
                            }
                        }
                    }
                }
                if failed{
                    dispatch_async(dispatch_get_main_queue(), { 
                        self.submitting = false
                        self.submitBtn.enabled = true
                        self.submitBtn.setTitle("提交订单", forState: .Normal)
                        self.submitBtn.backgroundColor = UIColor.orangeColor()
                        self.loadingSpinner.alpha = 0
                        UIAlertView(title: "提交失败", message: errMsg, delegate: nil, cancelButtonTitle: "OK").show()
                    })
                }
            }).resume()
        }else{
            print("json error")
        }
        
        
        
    }
    
    func handlePayment(){
        let amount = Int(totalPrice*100)
        if amount != 0 {
            let postDic = NSMutableDictionary()
            postDic.setObject(String(amount), forKey: "amount")
            postDic.setObject(Fatcat.payMethods[payMethod], forKey: "channel")
            let postJson = try?  NSJSONSerialization.dataWithJSONObject(postDic, options: .PrettyPrinted)
            
            if postJson != nil{
                print(NSString(data: postJson!, encoding: NSUTF8StringEncoding))
                
                // TODO: 支付请求
                
                let resq = NSMutableURLRequest(URL: NSURL(string: "http://218.244.151.190/demo/charge")!)
                resq.HTTPMethod = "POST"
                resq.HTTPBody = postJson
                resq.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
                
                NSURLSession.sharedSession().dataTaskWithRequest(resq, completionHandler: { (reData:NSData?, resp:NSURLResponse?, err:NSError?) in
                    self.retryBtn.alpha = 1
                    if err == nil{
                        if let data = reData{
                            let charge = NSString(data: data, encoding: NSUTF8StringEncoding)
                            Pingpp.createPayment(charge, viewController: self, appURLScheme: "autoprint", withCompletion: { (res:String!, err:PingppError!) in
                                if err == nil{
                                    dispatch_async(dispatch_get_main_queue(), {
                                        // MARK:支付成功
                                        //UIAlertView(title: res, message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                                        self.statusIcon.image = UIImage(named: "tick")
                                        self.statusIcon.alpha = 1
                                        self.actIndi.alpha = 0
                                        self.msgLabel.text = "支付成功"
                                        self.retryBtn.alpha = 0
                                        UIView.animateWithDuration(1, delay: 1, options: .CurveLinear, animations: {
                                            self.msgLabel.alpha = 0
                                            }, completion: { (finished2) in
                                                self.navigationController?.popViewControllerAnimated(true)
                                        })
                                        
                                        
                                    })
                                }else{
                                    dispatch_async(dispatch_get_main_queue(), {
                                        self.statusIcon.image = UIImage(named: "warning")
                                        self.statusIcon.alpha = 1
                                        self.actIndi.alpha = 0
                                        self.msgLabel.text = "支付未成功"
                                        
                                    })
                                }
                            })
                        }
                    }
                }).resume()
            }else{
                print("json encode error")
            }
        }
    }
    
    func jumpToPreViewFile(onlineFile: Bool, filePath: String, fileName: String) {
        // MARK:  点击预览按钮
        if onlineFile{
            presentViewController(HTMLStringViewController(path: filePath, name: fileName), animated: true, completion: nil)
        }else{
            let urlEncodeString = "file://\(filePath)".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
            let fileURL = NSURL(string: urlEncodeString)!
            let docPVC = UIDocumentInteractionController(URL: fileURL)
            docPVC.delegate = self
            docPVC.presentPreviewAnimated(true)
        }
    }
    
    
    func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
